package com.springboot.original.controller;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.springboot.original.common.exception.MessageElasticJobListener;
import com.springboot.original.common.utils.DateUtil;
import com.springboot.original.domain.StudentAnswerQuestionRecord;
import com.springboot.original.domain.StudentAnswerQuestionRecordKey;
import com.springboot.original.domain.User;
import com.springboot.original.service.DynamicAddJob;
import com.springboot.original.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.*;

@Controller
@Api(value = "列表展示", tags = "列表展示")
public class IndexController {

    @Value("${elastic.job.shardingTotalCount}")
    int shardingTotalCount;
    @Value("${elastic.job.shardingItemParameters}")
    String shardingItemParameters;
    @Autowired
    private UserService userService;
    @Autowired
    private ZookeeperRegistryCenter zookeeperRegistryCenter;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    /**
     * Go Index
     * @return
     */
    @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User"),
            @ApiImplicitParam(name = "code", value = "code", dataType = "String")
    })
    public String index(ModelMap model) {

        User user = userService.selectByPrimaryKey("Eiofn4dsB");
        System.out.println(user);

        User user2 = userService.selectByNickName("zzming");
        System.out.println(user2);

        String p = userService.getFromRedis("aaa");
        System.out.println(p);

        String a = "记录日志2";

        ListenableFuture future = kafkaTemplate.send("test1", a);

        future.addCallback(o -> System.out.println("send-消息发送成功!"), throwable -> System.out.println("消息发送失败"));

        model.addAttribute("user", user);

        return "index";
    }

    @RequestMapping(value = {"/savecassandra"}, method = RequestMethod.GET)
    @ResponseBody
    public String savecassandra() {

        for (int i = 0; i < 70000; i++) {
            StudentAnswerQuestionRecord studentAnswerQuestionRecord = new StudentAnswerQuestionRecord();
            StudentAnswerQuestionRecordKey studentAnswerQuestionRecordKey = new StudentAnswerQuestionRecordKey();
            studentAnswerQuestionRecordKey.setStudentId(UUID.randomUUID().toString().replaceAll("-", ""));
            studentAnswerQuestionRecordKey.setQuestionId(UUID.randomUUID().toString().replaceAll("-", ""));
            studentAnswerQuestionRecordKey.setTaskId(UUID.randomUUID().toString().replaceAll("-", ""));
            studentAnswerQuestionRecord.setpKey(studentAnswerQuestionRecordKey);
            studentAnswerQuestionRecord.setStudentName("批量保存测试数据无实际意义");
            studentAnswerQuestionRecord.setCityCode("0251");
            studentAnswerQuestionRecord.setStudentUid(UUID.randomUUID().toString().replaceAll("-", ""));
            studentAnswerQuestionRecord.setAnswerContent("写入大量数据测试无实际意义" + i);

            userService.addForCassandra(studentAnswerQuestionRecord);

            System.out.println("写入第 " + i + " 条");
        }

        return "success";
    }

    @RequestMapping(value = {"/truncatecassandra"}, method = RequestMethod.GET)
    @ResponseBody
    public String truncatecassandra() {

        userService.truncateForCassandra();

        return "删除成功";
    }

    @RequestMapping(value = {"/addjob"}, method = RequestMethod.GET)
    @ResponseBody
    public String addjob(@RequestParam("hour") int hour, @RequestParam("minute") int minute, @RequestParam("second") int second, @RequestParam("para") String para) {
        String cron = DateUtil.getCron(DateUtil.getTodayHourMinSec(hour, minute, second));
        System.out.println("【定时任务执行的时间】cron= " + cron);

        String jobName = UUID.randomUUID().toString() + "- zzm";
        JobCoreConfiguration jobCoreConfiguration = JobCoreConfiguration.newBuilder(jobName, cron, shardingTotalCount).jobParameter(para).misfire(true).shardingItemParameters(shardingItemParameters).jobProperties("job_exception_handler", "com.springboot.original.common.exception.CustomJobExceptionHandler").build();
        SimpleJobConfiguration simpleJobConfiguration = new SimpleJobConfiguration(jobCoreConfiguration, DynamicAddJob.class.getCanonicalName());
        JobScheduler jobScheduler = new JobScheduler(zookeeperRegistryCenter, LiteJobConfiguration.newBuilder(simpleJobConfiguration).build(), new MessageElasticJobListener());
        try {
            jobScheduler.init();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("定时任务创建失败");

        }

        return "success";
    }


    @RequestMapping(value = {"/writeFiles"}, method = RequestMethod.GET)
    @ResponseBody
    public String writeFiles(@RequestParam("directory") String directory, @RequestParam("filename") String filename) {

        File file2 = new File(directory, filename);
        if (!file2.exists()) {
            try {
                file2.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //向指定文件中写入文字
        FileWriter fileWriter;
        try {
            fileWriter = new FileWriter(directory + filename);
            //使用缓冲区比不使用缓冲区效果更好，因为每趟磁盘操作都比内存操作要花费更多时间。
            //通过BufferedWriter和FileWriter的连接，BufferedWriter可以暂存一堆数据，然后到满时再实际写入磁盘
            //这样就可以减少对磁盘操作的次数。如果想要强制把缓冲区立即写入,只要调用writer.flush();这个方法就可以要求缓冲区马上把内容写下去
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            List<StudentAnswerQuestionRecord> questionRecords = userService.getAllForCassandra();
            for (int i = 0; i < questionRecords.size(); i++) {
                bufferedWriter.write(questionRecords.get(i).getpKey().toString());
                System.out.println("写入第 " + i);
            }

            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "success";
    }


    @RequestMapping(value = {"/readFiles"}, method = RequestMethod.GET)
    @ResponseBody
    public String readFiles(@RequestParam("filePath") String filePath) {

        ExecutorService executor = new ThreadPoolExecutor(50, Integer.MAX_VALUE, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());
        Long a = Calendar.getInstance().getTimeInMillis();
        int count = 0;
        try {
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt;
                Future<StudentAnswerQuestionRecordKey> future = null;
                while ((lineTxt = br.readLine()) != null) {
                    count ++;
                    String[] keys = lineTxt.split("    ");
                    StudentAnswerQuestionRecordKey studentAnswerQuestionRecordKey = new StudentAnswerQuestionRecordKey();
                    studentAnswerQuestionRecordKey.setStudentId(keys[0]);
                    studentAnswerQuestionRecordKey.setTaskId(keys[1]);
                    studentAnswerQuestionRecordKey.setQuestionId(keys[2]);

                    PushTaskItemTread pushTaskItemTread = new PushTaskItemTread(studentAnswerQuestionRecordKey, userService,count);

                    future = executor.submit(pushTaskItemTread);
                }
                br.close();
                future.get();
            } else {
                System.out.println("文件不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
            Long b = Calendar.getInstance().getTimeInMillis();
            System.out.println("执行结束，共执行 "+count+" 条，共耗时 ： " + (b-a)/1000 +" s");
        }

        return "success";
    }


}